//
//  HRTakeAddressViewController.m
//  haierapp
//
//  Created by Xia Zhiyong on 14-8-12.
//  Copyright (c) 2014年 haier. All rights reserved.
//

#import "HRTakeAddressViewController.h"
#import "HRTakeAddressTableViewCell.h"
#import "HRTakeAddressTableHeadView.h"
#import "HRCreateNewAddressViewController.h"
#import "HREditAddressViewController.h"
#import "HRAddressList.h"

@interface HRTakeAddressViewController (){
    NSMutableArray *arrayTable;
    
    NSInteger delSection;  //要删除的地址所在section
}

@end

@implementation HRTakeAddressViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        arrayTable = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if (__CUR_IOS_VERSION >= __IPHONE_7_0)
    {
        self.edgesForExtendedLayout= UIRectEdgeNone;
    }
    self.navigationItem.title = @"收货地址";

    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"新建" style:UIBarButtonItemStylePlain target:self action:@selector(createNewAddress)];
    [self.navigationItem setRightBarButtonItem:rightItem];
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    view.backgroundColor = [UIColor clearColor];
    _tableView.tableFooterView = view;
    [self loadData];
}

-(void)loadData{
    //隐藏为空提示
    [self hideHud];
    
    [self showCustomLoadingHud:kLoading inView:nil];
    [arrayTable removeAllObjects];
    [HRInterfaceManager getReceiveAddressList:^(BOOL isSucceed, NSString *message, id data) {
        
        [self hideCustomLoadingHud];
        
        if (isSucceed) {
            HRAddressList *model = (HRAddressList*)data;
            [arrayTable addObjectsFromArray:model.list];
            [_tableView reloadData];
        }else if([message isEqualToString:NO_WIFI_ERROR_CODE]){
            [self showHudByType:HUDTYPE_NO_WIFI];
            return;
        }else{
            [self showTextHUD:message];
        }
        
        if (arrayTable==nil || [arrayTable count]==0) {
            //显示为空提示
            [self showHudByType:HUDTYPE_ADDRESS];
        }
        
        //页面加载耗时
        [self analysisEnd:nil];

    }];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - TableView

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [arrayTable count];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section<arrayTable.count) {
        return 36;
    }
    return 0;
}

-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    HRAddressInfo *info = [arrayTable objectAtIndex:section];
    HRTakeAddressTableHeadView *viewHead = [[HRTakeAddressTableHeadView alloc] init];
    if ([info.defaultAddress isEqualToString:@"1"]) {
        viewHead.btnSetNormal.selected = YES;
    }
    viewHead.btnClickWithAcition = ^(int actionType){
        switch (actionType) {
            case ACTION_SET_DEFAULT:{
                [self showCustomLoadingHud:kLoading inView:nil];
                [HRInterfaceManager setDefaultAddress:((HRAddressInfo*)[arrayTable objectAtIndex:section]).receiveAddressId completion:^(BOOL isSucceed, NSString *message, id data) {
                    [self hideCustomLoadingHud];
                    if (isSucceed) {  //  设置成功后刷新页面
                        
                        [self showSuccessHud:@"设置默认地址成功"];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(HUD_DELAY_HIDE_SECOND * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [self loadData];
                        });
                    }else{
                        [self showTextHUD:message];
                    }
                }];
            }
                break;
            case ACTION_EDIT:{
                HREditAddressViewController *viewC = [[HREditAddressViewController alloc] initWithNibName:@"HREditAddressViewController" bundle:nil];
                viewC.info = (HRAddressInfo*)[arrayTable objectAtIndex:section];
                viewC.addressChange = ^(){ //编辑页面地址信息变化后刷新列表
                    [self loadData];
                };
                [self.navigationController pushViewController:viewC animated:YES];
                break;
            }
            case ACTION_DEL:{
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"确定删除该收货地址?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                delSection = section;
                [alert show];
            }
                
            default:
                break;
        }
    };
    return viewHead;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 65;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"HRTakeAddressTableViewCell";
    HRTakeAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[HRTakeAddressTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    [cell configWithData:[arrayTable objectAtIndex:indexPath.section]];
    return cell;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

//新建地址
-(void)createNewAddress{
    HRCreateNewAddressViewController *viewC = [[HRCreateNewAddressViewController alloc] initWithNibName:@"HRCreateNewAddressViewController" bundle:nil];
    viewC.createAddressSucced = ^(){
        [self loadData];
    };
    [self.navController pushViewController:viewC animated:YES];
}

#pragma mark - HRProgress Delegate Methods
//新建地址、重新加载
-(void)tapHUDButtonAction:(id)button{
    
    UIButton *theButton=(UIButton *)button;
    
    if ([theButton.titleLabel.text isEqualToString:@"重新加载"]) {
        [self loadData];
    }else{
        //新建地址
        [self createNewAddress];
    }
}

#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        [self showCustomLoadingHud:kLoading inView:nil];
        [HRInterfaceManager deleteReceiveAddressById:((HRAddressInfo*)[arrayTable objectAtIndex:delSection]).receiveAddressId completion:^(BOOL isSucceed, NSString *message, id data) {
            [self hideCustomLoadingHud];
            
            if (isSucceed) {
                [arrayTable removeObjectAtIndex:delSection];
                [_tableView reloadData];
                if (arrayTable.count == 0) {
                    [self showHudByType:HUDTYPE_ADDRESS];
                }
                [self showSuccessHud:@"删除成功"];
            }else{
                [self showTextHUD:message];
            }
        }];

    }
}

@end
